﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using IKEA.FileExchange.Domain.FilePackage;
using Microsoft.SharePoint;
using IKEA.FileExchange.Domain;
using IKEA.FileExchange.Domain.Files;
using System.Collections.Generic;
using IKEA.FileExchange.Domain.DownloadTickets;
using Microsoft.SharePoint.WebControls;
using IKEA.FileExchange.Web;

public partial class controls_FilePackageManagerControl : System.Web.UI.UserControl
{

    protected SPListItem FilePackageListItem;
    protected FilePackageInformation PackageInformation;
    protected SPListItemCollection Files;


    public class RecipientStatusInformation
    {
        public string RecipientEmail;
        public string StatusString;
        public bool IsActive;
    }

    public class FilePackageDownloadTicket
    {
        public string Title;
        public string IKEAFilePackageReference;
        public string DownloadTicketOwnerEmail;
    }

    public class FileItem
    {
        public string FileName;
        public string FileSize;
        public string FileDeletionDate;
        public string FileUniqueId;
        public string FileUrl;
        public string DownloadUrl;
    }

    public class DownloadHistoryItem
    {
        public string Recipient;
        public string FileName;
        public string DownloadStartTime;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        hlOpenDownloadReport.NavigateUrl = "~/DownloadReport.aspx?p=" + Request.QueryString["p"];

     //   FilePackageListItem[FilePackageFieldNames.UploadComments]

        if (!IsPostBack)
        {
            PopulatePackageData();

            if (PackageInformation.IsConfidential)
            {
                ltrlStoreType.Text = "the confidential files store";
            }
            else
            {
                ltrlStoreType.Text = "the public file store";
            }
        }
    }

    protected void UpdatePackageInformation()
    {
        PackageInformation = FilePackageInformationProvider.Extract(FilePackageListItem);
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        gvRecipientStatuses.RowDataBound += new GridViewRowEventHandler(gvRecipientStatuses_RowDataBound);

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    Guid packageUniqueId = new Guid(Request.QueryString["p"]);

                    SPList packageList = IKEAFileStoreHelper.GetFilePackagesList(spWeb);

                    FilePackageListItem = packageList.GetItemByUniqueId(packageUniqueId);

                    UpdatePackageInformation();
                }
            }
        }
        );
    }

    void gvRecipientStatuses_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton lb = (LinkButton)e.Row.FindControl("lbResend");

            RecipientStatusInformation statusInfo = (RecipientStatusInformation)e.Row.DataItem;

            lb.Attributes.Add("RecipientEmail", statusInfo.RecipientEmail);
        }
    }




    protected void lbResend_Click(object sender, EventArgs e)
    {
        LinkButton lbResend = (LinkButton)sender;

        string recipientEmail = lbResend.Attributes["RecipientEmail"];

      
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    SPListItem ticket = DownloadTicketManager.GetDownloadTicket(recipientEmail, FilePackageListItem.Title, spWeb);

                    FilePackageDownloadTicket tkt = new FilePackageDownloadTicket();

                    tkt.Title = ticket["Title"].ToString();
                    tkt.DownloadTicketOwnerEmail = ticket["DownloadTicketOwnerEmail"].ToString();
                    tkt.IKEAFilePackageReference = ticket["IKEAFilePackageReference"].ToString();


                    EmailHelper.SendEmail(tkt.DownloadTicketOwnerEmail, tkt.Title, "", NotificationType.NotificationToRecipient, spWeb);
                }
            }
        }
        );

    }

    protected void PopulateRecipientsAndDownloadsSection(FilePackageInformation packageInformation, SPListItem packageItem, SPWeb spWeb)
    {
        List<string> recipientsList = packageInformation.GetRecipients();

        List<RecipientStatusInformation> dataSource = new List<RecipientStatusInformation>();

        foreach (string recipient in recipientsList)
        {
            RecipientStatusInformation statusInfo = new RecipientStatusInformation();
            statusInfo.RecipientEmail = recipient;

            statusInfo.StatusString = "0/" + Files.Count.ToString();

            statusInfo.IsActive = true;

            dataSource.Add(statusInfo);
        }

        gvRecipientStatuses.DataSource = dataSource;
        gvRecipientStatuses.DataBind();
    }

    protected void PopulateFilesList(FilePackageInformation packageInformation, SPListItem packageItem, SPWeb spWeb)
    {
        SPQuery q = new SPQuery();

        SPFieldLookupValue lookupValue = new SPFieldLookupValue(packageItem.ID, packageItem.Title);

        string queryText = string.Format("<Where><Eq><FieldRef Name='{0}'/><Value Type='Text'>{1}</Value></Eq></Where>",
            "IKEAFilePackageReference", lookupValue.LookupValue);

        

        q.Query = queryText;
        q.ViewAttributes = "Scope=\"Recursive\"";
        


        SPList fileStore = null;

        if (packageInformation.IsConfidential)
        {
            fileStore = IKEAFileStoreHelper.GetConfidentialFileStore(spWeb);
        }
        else
        {
            fileStore = IKEAFileStoreHelper.GetPublicFileStore(spWeb);
        }

        SPListItemCollection files = fileStore.GetItems(q);
        List<FileItem> filesDataSource = new List<FileItem>();

        this.Files = files;

        foreach (SPListItem file in files)
        {
            FileItem fi = new FileItem();

            filesDataSource.Add(fi);

            fi.FileDeletionDate = file[FileFieldNames.FileDeletionDate].ToString();
            fi.FileName = file.File.Name;
            fi.FileUrl = Page.ResolveClientUrl("~/_layouts/images/" + file.File.IconUrl);

            int fileSizeInBytes = int.Parse(file["File Size"].ToString());
            fi.FileSize = ( (long) (fileSizeInBytes / (1024 ) ) ).ToString() + " KB";

            fi.FileUniqueId = file.UniqueId.ToString();

            string downloadUrl = string.Format("~/_layouts/FileExchangeLayouts/services/DownloadFilesByManager.aspx?p={0}&f={1}",
                packageItem.UniqueId.ToString(),file.UniqueId.ToString());
            fi.DownloadUrl = Page.ResolveClientUrl(downloadUrl);
        }



        gvFiles.DataSource = filesDataSource;
        gvFiles.DataBind();
    }

    protected void ShowCommentsText()
    {
        lbChangeComments.Visible = true;
        lblUploadComments.Visible = true;

        txtUploadComments.Visible = false;
        tblApplyComments.Visible = false;
        tblCancelCommentsChanging.Visible = false;
    }

    protected void btnCancelComments_Click(object sender, EventArgs e)
    {
        ShowCommentsText();
    }

    protected void lbChangeComments_Click(object sender, EventArgs e)
    {
        lbChangeComments.Visible = false;
        lblUploadComments.Visible = false;

        txtUploadComments.Visible = true;
        tblApplyComments.Visible = true;
        tblCancelCommentsChanging.Visible = true;

        txtUploadComments.Text = PackageInformation.UploadComments;
    }

    protected void btnApplyComments_Click(object sender, EventArgs e)
    {
        ShowCommentsText();   


        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            FilePackageListItem[FilePackageFieldNames.UploadComments] = txtUploadComments.Text;
            FilePackageListItem.Update();

            UpdatePackageInformation();
            lblUploadComments.Text = PackageInformation.UploadComments;            
        }
        );
    }

    protected void PopulatePackageData()
    {
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {

                    ltrlCreateDate.Text = FilePackageListItem["Created"].ToString();

                    lblUploadComments.Text = PackageInformation.UploadComments;

                    PopulateFilesList(PackageInformation, FilePackageListItem,
                        spWeb);

                    PopulateRecipientsAndDownloadsSection(PackageInformation, FilePackageListItem, spWeb);

                }
            }
        }
        );
    }

    protected void lbAddRecipients_Click(object sender, EventArgs e)
    {
        lbAddRecipients.Visible = false;

        divNewRecipients.Visible = true;
    }

    protected void btnCancelRecipients_Click(object sender, EventArgs e)
    {
        lbAddRecipients.Visible = true;

        divNewRecipients.Visible = false;
    }


    protected void btnApplyRecipients_Click(object sender, EventArgs e)
    {
        lbAddRecipients.Visible = true;

        divNewRecipients.Visible = false;

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    string[] newRecipients = txtRecipients.Text.Split(';');

                    string recipientsRaw = PackageInformation.RecipientsRaw + ";" + txtRecipients.Text;

                    FilePackageListItem[FilePackageFieldNames.FilePackageRecipients] = recipientsRaw;               

                    FilePackageListItem.Update();

                    UpdatePackageInformation();

                    PopulateFilesList(PackageInformation, FilePackageListItem, spWeb);

                    PopulateRecipientsAndDownloadsSection(PackageInformation, FilePackageListItem, spWeb);

                    Dictionary<string, Guid> newDownloadTickets = DownloadTicketManager.CreateDownloadTickets(FilePackageListItem, spWeb, newRecipients);

                    foreach (KeyValuePair<string, Guid> recipientTicket in newDownloadTickets)
                    {
                        EmailHelper.SendEmail(recipientTicket.Key, recipientTicket.Value.ToString(), txtUploadComments.Text, NotificationType.NotificationToRecipient, spWeb);
                    }
                }
            }
        }
        );
    }
}
